package com.apeli.web.controller.aticle;

import com.apeli.common.core.domain.AjaxResult;
import com.apeli.common.utils.SecurityUtils;
import com.apeli.common.utils.StringUtils;
import com.apeli.common.utils.file.AliyunOssUtils;
import com.apeli.system.domain.Comment;
import com.apeli.system.domain.vo.ArticleVO;
import com.apeli.system.domain.vo.ImageVO;
import com.apeli.system.service.ArticleService;
import com.apeli.system.service.ISysTagService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;

/**
 * 文章controller
 *
 * @author apeli
 *
 * @date 2022 -03-02
 */
@RestController
@RequestMapping("/article")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ArticleController {

    private final ISysTagService sysTagService;

    private final ArticleService articleService;

    private final AliyunOssUtils utils;

    @GetMapping("/tags")
    public AjaxResult queryArticleTags() {
        return AjaxResult.success(sysTagService.queryTag());
    }

    @PostMapping("/image")
    public AjaxResult uploadImage(MultipartFile file) throws IOException {
        String data = utils.uploadFile(file);
        String imageUrl = utils.generatePresignedUrl(data);
        ImageVO imageVO = new ImageVO();
        imageVO.setImagePath(data);
        imageVO.setImageUrl(imageUrl);
        return AjaxResult.success(imageVO);
    }

    @PostMapping("/addArticle")
    public AjaxResult addArticle(@RequestBody @Valid ArticleVO articleVO) {
        return articleService.addArticle(articleVO);
    }

    @GetMapping("/listArticle")
    public AjaxResult listArticle () {
        return AjaxResult.success(articleService.listArticle(null));
    }

    @GetMapping("/listArticleByUserId")
    public AjaxResult listArticleByUserId() {
        Long userId = SecurityUtils.getUserId();
        return AjaxResult.success(articleService.listArticle(userId));
    }

    @PostMapping("/changeStatus/{articleId}/{status}")
    public AjaxResult changeStatus(@PathVariable Long articleId,@PathVariable Integer status) {
        return articleService.changeStatus(articleId,status);
    }

    @GetMapping("/{id}")
    public AjaxResult queryArticleById (@PathVariable Long id) {
        return AjaxResult.success(articleService.queryArticleById(id));
    }

    @PostMapping("/commentsArticle")
    public AjaxResult commentsArticle(@RequestBody Comment comment) {
        if (StringUtils.isBlank(comment.getContent())) {
            return AjaxResult.error("评论内容必填");
        }
        return articleService.commentArticle(comment.getContent(),comment.getArticleId());
    }
}
